package application.exportimport;

import dao.inte.ProductRepository;
import domain.shop.Product;
import org.springframework.beans.factory.annotation.Autowired;

import javax.inject.Singleton;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;

@Singleton
public class DatabaseImporter {

    @Autowired
    private ProductRepository productRepository;

    public DatabaseImporter() {
    }

    public void importProducts(InputStream is) throws JAXBException, FileNotFoundException, Exception {
        JAXBContext jaxbContext = JAXBContext.newInstance(ImportXMLWrapper.class);
        Unmarshaller u = jaxbContext.createUnmarshaller();
        ImportXMLWrapper importXMLWrapper = (ImportXMLWrapper) u.unmarshal(is);
        saveProducts(importXMLWrapper);
    }

    private void saveProducts(ImportXMLWrapper importXMLWrapper) throws Exception {
        List<Product> products = importXMLWrapper.getProducts();
        for (Product product : products) {
            productRepository.save(product);
        }
    }

    @XmlRootElement(name = "SHOP")
    private static class ImportXMLWrapper extends AbstractXmlWrapper {

        List<Product> products;

        public ImportXMLWrapper() {
        }

        @XmlElement(name = "SHOPITEM")
        public List<Product> getProducts() {
            return products;
        }

        public void setProducts(List<Product> products) {
            this.products = products;
        }
    }
}
